package com.qf.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Wy
 * @version V1.0
 * @Project MavenDemo
 * @Package com.qf.filter
 * @Description:
 * @Date 2022/7/7 17:35
 */
@Component
public class MyGlobalFilter implements GlobalFilter,Ordered{

    /**
     * 这个方法中编写过滤器中执行的业务逻辑, 比如鉴权,授权工作
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("----全局过滤器---");
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //获取请求字符串
        String token = request.getHeaders().getFirst("token");
        //2.如果token为空，则拦截
         if(StringUtils.isBlank(token)){
             //装异常进去
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
             //给前端响应异常
            return  response.setComplete();
         }
        //3. 如果获取到token就认为有权限访问放行
        //放行, 继续执行下一个过滤器
        return chain.filter(exchange);
    }
    /**
     * 返回的数字, 就是如果有多个过滤器, 他们的执行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
